package com.xoa.service.footprint.impl;


import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.footprint.FootPrintMapper;
import com.xoa.model.department.Department;
import com.xoa.model.footprint.Foot;
import com.xoa.model.footprint.LngLat;
import com.xoa.service.footprint.FootPrintService;
import com.xoa.util.CoodinateCovertor;
import com.xoa.util.DateFormat;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.page.PageParams;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @创建作者: 韩成冰
 * @创建日期: 2017/6/8 11:06
 * @类介绍: 我的足迹
 * @构造参数: 无
 **/

@Service
public class FootPrintServiceImpl implements FootPrintService {

    //查询我的足迹
    private static final String GET_MY_FOOTPRINT = "1";
    //查询我所在的部门的人员足迹
    private static final String GET_DEPT_FOOTPRINT = "2";

    @Resource
    private FootPrintMapper footPrintMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    /**
     * @创建作者: 韩成冰
     * @创建日期: 2017/6/8 11:07
     * @函数介绍: 添加足迹
     * @参数说明: @param Foot
     * @return: void
     */
    @Override
    @Transactional
    public ToJson<Foot> addFootPrint(Foot foot) {
        ToJson<Foot> toJson =new ToJson<Foot>();
        try {
            footPrintMapper.addFootPrint(foot);
            toJson.setFlag(0);
            toJson.setMsg("ok");
            toJson.setObject(foot);
        }catch (Exception e){
            toJson.setFlag(1);
            toJson.setMsg("error");
        }
        return toJson;
    }

    /**
     * @创建作者: 韩成冰
     * @创建日期: 2017/6/8 13:24
     * @函数介绍: 查询足迹
     * @参数说明: @param Integer app : 1是查询我的足迹，2是查我所在的部门的同事足迹，3查询全部
     * @参数说明: @param Integer uid
     * @return: List<Foot></Foot>
     */
    @Override
    public List<Foot> getFootPrint(String app, Integer uid, String pageNum) {

        Integer currentpage;
        Integer start;
        //分页
        if (pageNum == null) {
            currentpage = 0;
            start = 0;
        } else {
            currentpage = Integer.parseInt(pageNum);
           start = (currentpage - 1) * 10;
        }


        List<Foot> list = null;

        //获取我的部门信息
        List<Department> departmentList = null;
        if (GET_DEPT_FOOTPRINT.equals(app)) {
            departmentList = departmentMapper.getDepartmentByUid(uid);
        }

        //查询我的部门足迹
        if (GET_DEPT_FOOTPRINT.equals(app)) {
            //我所在的只有一个部门
            if (departmentList != null && departmentList.size() == 1) {
                Department department = departmentList.get(0);
                if (department != null && department.getDeptId() != null) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("deptId", department.getDeptId());
                    map.put("currentpage", start);
                    list = footPrintMapper.getFootPrintByDepId(map);
                }
            }
            //查询我的足迹
        } else if (GET_MY_FOOTPRINT.equals(app)) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("uid", uid);
            map.put("currentpage", start);
            list = footPrintMapper.getFootPrintByUid(map);

            //查询所有
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("currentpage", start);
            list = footPrintMapper.getAllFootPrint(map);
        }
        return list;
    }

    /**
     * @创建作者: 韩成冰
     * @创建日期: 2017/6/8 15:15
     * @函数介绍: 查询某一条足迹
     * @参数说明: @param day 足迹时间格式比如：2017-06-07
     * @参数说明: @param uid
     * @return: Foot
     */
    @Override
    public List<Foot> getTheFootPrint(String dayStr, Integer uid) throws ParseException {

        if (dayStr == null || uid == null) {
            return null;
        }


        //获取该日的其实时间的秒值和结束时间的秒值
        String startTime = dayStr.concat(" 00:00:00");
        String endTime = dayStr.concat(" 23:59:59");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date start = sdf.parse(startTime);
        Date end = sdf.parse(endTime);

        Long beginDayTime = (start.getTime() / 1000);
        Long endDayTime = (end.getTime() / 1000);

        int startDay = beginDayTime.intValue();
        int endDay = endDayTime.intValue();

        Map<String, Integer> hashMap = new HashMap<String, Integer>();
        hashMap.put("startDay", startDay);
        hashMap.put("endDay", endDay);
        hashMap.put("uid", uid);
        List<Foot> footList = footPrintMapper.getUserDayFootPrint(hashMap);

        return footList;
    }

    /**
     * @创建作者: 韩成冰
     * @创建日期: 2017/6/13 17:42
     * @函数介绍: 按条件查询用户
     * @参数说明: @param condition 查询条件，可能是用户名， 部门， 或时间
     * @参数说明: @param app 查询条件，可能是用户名， 部门， 或时间
     * @参数说明: @param pageNum 分页
     * @return: List<Foot></Foot>
     **/
    @Override
    public List<Foot> findByCondition(String condition, String app, String pageNum, Integer uid) {

        //无条件
        if (condition == null || "".equals(condition)) {
            return getFootPrint(app, uid, pageNum);
        }

        Integer currentpage;
        Integer start;
        //分页
        if (pageNum == null) {
            currentpage = 0;
            start = 0;
        } else {
            currentpage = Integer.parseInt(pageNum);
            start = (currentpage - 1) * 10;
        }
        List<Foot> list = new ArrayList<Foot>();

        //用户的查询条件是数字，就是根据时间查询
        boolean flag = true;
        //先判断用户输入的是否可能是时间，如果是时间的话就按时间作为条件查询
        Integer number = null;
        try {
            number = Integer.parseInt(condition);
        } catch (Exception e) {
            flag = false;
        }

        //非时间查询情况
        if (!flag) {

            //获取我的部门信息
            List<Department> departmentList = null;
            if (GET_DEPT_FOOTPRINT.equals(app)) {
                departmentList = departmentMapper.getDepartmentByUid(uid);
            }
            //查询我的部门足迹
            if (GET_DEPT_FOOTPRINT.equals(app)) {
                if (departmentList != null && departmentList.size() == 1) {
                    Department department = departmentList.get(0);
                    if (department != null && department.getDeptId() != null) {

                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("deptId", department.getDeptId());
                        map.put("currentpage", start);
                        map.put("condition", "%".concat(condition).concat("%"));
                        list = footPrintMapper.getDeptFootPrintByCondition(map);
                    }
                }
                //查询我的足迹
            } else if (GET_MY_FOOTPRINT.equals(app)) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("uid", uid);
                map.put("currentpage", start);
                list = footPrintMapper.getFootPrintByUid(map);

                //查询所有
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("currentpage", start);
                map.put("condition", "%".concat(condition).concat("%"));
                list = footPrintMapper.getAllFootPrintByCondition(map);
            }

            //按时间查询
        } else {

            //获取我的部门信息
            List<Department> departmentList = null;
            if (GET_DEPT_FOOTPRINT.equals(app)) {
                departmentList = departmentMapper.getDepartmentByUid(uid);
            }
            //查询我的部门足迹
            if (GET_DEPT_FOOTPRINT.equals(app)) {
                if (departmentList != null && departmentList.size() == 1) {
                    //获取我的部门
                    Department department = departmentList.get(0);
                    if (department != null && department.getDeptId() != null) {

                        try {
                            //用户传入时间字符串可能对于的情况，比如12可以是2012-xx-xx,或xxxx-12-xx 或 xxxx-xx-12
                            List<Map<String, Long>> mapList = paseDateCondition("" + number);

                            for (Map<String, Long> map : mapList) {
                                Long dayStartSecond = map.get("dayStartSecond");
                                Long dayEndSecond = map.get("dayEndSecond");

                                Map<String, Object> hashMap = new HashMap<String, Object>();
                                hashMap.put("deptId", department.getDeptId());
                                hashMap.put("dayStartSecond", dayStartSecond);
                                hashMap.put("dayEndSecond", dayEndSecond);
                                List<Foot> eachTimeList = new ArrayList<Foot>();
                                eachTimeList = footPrintMapper.getDeptFootPrintByTime(map);

                                //把每次查询的放到list里
                                if (eachTimeList != null) {
                                    for (Foot foot : eachTimeList) {
                                        list.add(foot);
                                    }

                                }
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                //查询我的足迹
            } else if (GET_MY_FOOTPRINT.equals(app)) {
                try {
                    List<Map<String, Long>> mapList = paseDateCondition("" + number);

                    for (Map<String, Long> map : mapList) {
                        Long dayStartSecond = map.get("dayStartSecond");
                        Long dayEndSecond = map.get("dayEndSecond");
                        Map<String, Object> hashMap = new HashMap<String, Object>();
                        hashMap.put("uid", uid);
                        hashMap.put("currentpage", start);
                        hashMap.put("dayStartSecond", dayStartSecond);
                        hashMap.put("dayEndSecond", dayEndSecond);
                        List<Foot> eachTimeList = new ArrayList<Foot>();
                        eachTimeList = footPrintMapper.getFootPrintByUidTime(hashMap);
                        //把每次查询的放到list里
                        if (eachTimeList != null) {
                            for (Foot foot : eachTimeList) {
                                list.add(foot);
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                //查询所有
            } else {

                try {
                    List<Map<String, Long>> mapList = paseDateCondition("" + number);

                    for (Map<String, Long> map : mapList) {
                        Map<String, Object> hashMap = new HashMap<String, Object>();
                        hashMap.put("currentpage", start);
                        hashMap.put("condition", condition);
                        hashMap.put("uid", uid);
                        Long dayStartSecond = map.get("dayStartSecond");
                        Long dayEndSecond = map.get("dayEndSecond");
                        hashMap.put("dayStartSecond", dayStartSecond);
                        hashMap.put("dayEndSecond", dayEndSecond);
                        List<Foot> eachTimeList = new ArrayList<Foot>();
                        eachTimeList = footPrintMapper.getAllFootPrintByTime(hashMap);
                        //把每次查询的放到list里
                        if (eachTimeList != null) {
                            for (Foot foot1 : eachTimeList) {
                                list.add(foot1);
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    /**
     * @创建作者: 韩成冰
     * @创建日期: 2017/6/14 15:28
     * @参数说明: @param String day 时间
     * @参数说明: @param Integer uid 用户id
     * @函数介绍: 查询某人某天的足迹
     * @return: List<Foot></Foot>
     */
    @Override
    public List<Foot> getTheDayFootPrint(String day, Integer uid) {
        if (day != null && uid != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            //用户传的day格式是2012-12-12
            String startDayStr = day.concat(" 00:00:00");
            String endDayStr = day.concat(" 23:59:59");

            Date startDaySecond = null;
            try {
                startDaySecond = sdf.parse(startDayStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Date endDaySecond = null;
            try {
                endDaySecond = sdf.parse(endDayStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //数据库是秒值
            Long start = startDaySecond.getTime() / 1000;
            Long end = endDaySecond.getTime() / 1000;

            Map<String, Object> hashMap = new HashMap<String, Object>();
            hashMap.put("start", start);
            hashMap.put("end", end);
            hashMap.put("uid", uid);

           return footPrintMapper.getTheDayFootPrint(hashMap);
        }
        return null;
    }

    @Override
    public ToJson<Foot>  editUpdateTimeByuid(String time, Integer uid,Integer id) {
        ToJson<Foot> footToJson=new ToJson<Foot>();
        Foot foot= footPrintMapper.queryById(id);
        if(foot!=null){
         String a1= DateFormat.getStrTime(foot.getCreateTime());

            // Integer time1= DateFormat.getTime(time);
            //Integer time2=time1-foot.getCreateTime();
            int a=footPrintMapper.editFootByTime(Integer.parseInt(time),uid,id);
            footToJson.setMsg("ok");
            footToJson.setFlag(0);
           footToJson.setObject( DateFormat.returnTime(Integer.parseInt(time)-foot.getCreateTime()));

        }else {
        footToJson.setMsg("err");
        footToJson.setFlag(1);
        }
        return  footToJson;
    }

    /**
     * @创建作者: 韩成冰
     * @创建日期: 2017/6/13 18:03
     * @函数介绍: 用户输入的是查询条件类似时间时，获取该时间对应的天
     * 比如用户输入12 ，可能是2012-xx-xx, xxxx-12-xx ,xxxx-xx-12,找出对应时间的秒值
     * @参数说明: @param String number
     * @return: List<Map<String, Long>>
     **/
    public List<Map<String, Long>> paseDateCondition(String number) throws ParseException {

        List<Map<String, Long>> list = new ArrayList<Map<String, Long>>();

        //找出用户输入数字可能对应的时间
        List<String> dataStrList = new ArrayList<String>();
        String dateStr = "20";
        //20*
        for (int i = 17; i <= 50; i++) {
            dateStr = dateStr.concat("" + i);
            for (int k = 1; k <= 12; k++) {
                //0-9
                if (k < 10) {
                    dateStr = dateStr.concat("-0" + k);
                    //10-12
                } else {
                    dateStr = dateStr.concat("-" + k);
                }

                for (int l = 1; l <= 31; l++) {
                    //1-9
                    if (l < 10) {
                        dateStr = dateStr.concat("-0" + l);
                        if (dateStr.contains(number)) {
                            dataStrList.add(dateStr);
                        }
                    } else {

                        dateStr = dateStr.concat("-" + l);
                        if (dateStr.contains(number)) {
                            dataStrList.add(dateStr);
                        }
                    }
                    //2017-02-11，循环后去掉日
                    dateStr = dateStr.substring(0, 7);
                }
                //2017-02，循环后去掉月
                dateStr = dateStr.substring(0, 4);
            }
            //2017，循环后去掉年份后两位
            dateStr = dateStr.substring(0, 2);
        }

        //算出每天的开始和结束秒数
        for (String s : dataStrList) {

            String dayStart = s.concat(" 00:00:00");
            String dayEnd = s.concat(" 23:23:23");

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date dayStartTime = sdf.parse(dayStart);
            Long dayStartSecond = dayStartTime.getTime() / 1000;

            Date dayEndTime = sdf.parse(dayEnd);
            Long dayEndSecond = dayEndTime.getTime() / 1000;
            Map<String, Long> map = new HashMap<String, Long>();
            map.put("dayStartSecond", dayStartSecond);
            map.put("dayEndSecond", dayEndSecond);
            list.add(map);
        }
        return list;
    }

    /**
     * @创建作者: 韩成冰
     * @创建日期: 2017/6/8 13:24
     * @函数介绍: 查询足迹
     * @参数说明: @param Integer app : 1是查询我的足迹，2是查我所在的部门的同事足迹，3查询全部
     * @参数说明: @param Integer uid
     * @参数说明：@param String time 查询时间(年-月-日)
     * @参数说明：@param String detail 详情不需要分组，否则需要就行分组1-不需要进行分组，0-需要进行分组
     * @return: List<Foot></Foot>
     */
    @Override
    public ToJson<Foot> getWebFootPrint(String app,String time,String detail,Integer uid,Integer page, Integer pageSize, Boolean useFlag) {
          ToJson<Foot> json =new ToJson<Foot>();
        //分页处理
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        List<Foot> list = null;

        //获取我的部门信息
        List<Department> departmentList = null;
        try {
            String beginTime="";
            String endTime="";
            if(!StringUtils.checkNull(time)){
                beginTime=time+" 00:00:00";
                endTime=time+" 23:59:59";
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                beginTime=String.valueOf((format.parse(beginTime)).getTime()/1000);
                endTime=String.valueOf((format.parse(endTime)).getTime()/1000);
            }
            if (GET_DEPT_FOOTPRINT.equals(app)) {
                departmentList = departmentMapper.getDepartmentByUid(uid);
            }

            //查询我的部门足迹
            if (GET_DEPT_FOOTPRINT.equals(app)) {
                //我所在的只有一个部门
                if (departmentList != null && departmentList.size() == 1) {
                    Department department = departmentList.get(0);
                    if (department != null && department.getDeptId() != null) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("deptId", department.getDeptId());
                        map.put("page", pageParams);
                        map.put("time", time);
                        map.put("beginTime", beginTime);
                        map.put("endTime", endTime);
                        map.put("detail", detail);
                        list = footPrintMapper.getWebFootPrintByDepId(map);
                    }
                }
                //查询我的足迹
            } else if (GET_MY_FOOTPRINT.equals(app)) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("uid", uid);
                map.put("page", pageParams);
                map.put("time", time);
                map.put("beginTime", beginTime);
                map.put("endTime", endTime);
                list = footPrintMapper.getWebFootPrintByUid(map);
                for(Foot foot:list){
                    LngLat lngLat=new LngLat();
                    lngLat.setLantitude(Double.valueOf(foot.getLng()));
                    lngLat.setLongitude(Double.valueOf(foot.getLat()));
                    LngLat lngLat1= CoodinateCovertor.bd_encrypt(lngLat);
                    foot.setLantitude(String.valueOf(lngLat1.getLantitude()));
                    foot.setLongitude(String.valueOf(lngLat1.getLongitude()));
                }

                //查询所有
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("page", pageParams);
                map.put("time", time);
                map.put("beginTime", beginTime);
                map.put("endTime", endTime);
                map.put("detail", detail);
                list = footPrintMapper.getWebAllFootPrint(map);
            }

            json.setObj(list);
            json.setTotleNum(pageParams.getTotal());
            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setFlag(1);
            e.printStackTrace();
        }
        return json;

    }


}